import { Card, Input, message } from 'antd';

import type { UploadProps } from 'antd';

import { RcFile } from 'antd/es/upload';
import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';

import { AppCreateTypeEnum } from '@/common/app/constants';
import AppTagSelect from '@/components/AppTagSelect';
import { CustomFormLabel, PrefixStyleLabel } from '@/components/eai-design';
import Modals from '@/components/modals/Modals';
import { MongoImageTypeEnum } from '@/pages/chat/tools/constants';
import { compressImgFileAndUpload } from '@/types/app/api';

import '../work.scss';

import { DEFAULT_IMAGES } from './ImageDisplay';
import LogoSelector, { agentLogos, fusionLogos, workflowLogos } from './LogoSelector';
import { SceneImageType } from './SceneImageSelector';

interface AppCreateModalProps {
  open: boolean;
  appType: string;
  title?: string;
  defaultAppName?: string;
  defaultAppDescription?: string;
  defaultAppLogo?: string;
  defaultSceneImage?: string;
  onOk?: (data: {
    tag: string | undefined;
    appName: string;
    appDescription: string;
    appLogo: string;
    sceneImage: string;
    appLogoList: string[];
    sceneImageList: string[];
  }) => void;
  onCancel?: () => void;
}

const AppInfoModal: React.FC<AppCreateModalProps> = ({
  open,
  appType,
  title,
  defaultAppName = '',
  defaultAppDescription = '',
  defaultAppLogo = '',
  defaultSceneImage = '',
  onOk,
  onCancel,
}) => {
  const router = useNavigate();
  const [isShow, setIsShow] = useState<boolean>(false);
  const [isClick, setIsClick] = useState<boolean>(true);
  const [appNameConfig, setAppNameConfig] = useState<string>(defaultAppName);
  const [appTag, setAppTag] = useState<string>(null);
  const [appDescriptionConfig, setAppDescriptionConfig] = useState<string>(defaultAppDescription);
  const [appLogoConfig, setAppLogoConfig] = useState<string>(defaultAppLogo);
  const [sceneImageConfig, setSceneImageConfig] = useState<string>(defaultSceneImage);
  const [customLogos, setCustomLogos] = useState<string[]>([]);
  const [customSceneImages, setCustomSceneImages] = useState<string[]>([]);

  const [sceneImageOption, setSceneImageOption] = useState<'match' | 'custom'>(
    defaultSceneImage ? 'custom' : 'match',
  );
  const [logoLoading, setLogoLoading] = useState(false);
  const [sceneImageLoading, setSceneImageLoading] = useState(false);

  useEffect(() => {
    if (!defaultAppLogo) {
      if (appType === AppCreateTypeEnum.workflow) {
        setAppLogoConfig(workflowLogos[0].id);
      } else if (appType === AppCreateTypeEnum.fusion) {
        setAppLogoConfig(fusionLogos[0].id);
      } else if (appType === AppCreateTypeEnum.agent) {
        setAppLogoConfig(agentLogos[0].id);
      }
    }
  }, [defaultAppLogo, appType]);

  const defaultLogo = useMemo(() => {
    if (appType === AppCreateTypeEnum.workflow) {
      return workflowLogos[0].id;
    }
    if (appType === AppCreateTypeEnum.fusion) {
      return fusionLogos[0].id;
    }
    if (appType === AppCreateTypeEnum.agent) {
      return agentLogos[0].id;
    }
    return 'default';
  }, [appType]);

  useEffect(() => {
    if (open) {
      setIsShow(true);
      setCustomLogos((prev) => (defaultAppLogo ? [defaultAppLogo, ...prev] : prev));
      setCustomSceneImages((prev) => (defaultSceneImage ? [defaultSceneImage, ...prev] : prev));
    } else {
      setCustomLogos([]);
      setCustomSceneImages([]);
    }
    setAppNameConfig(defaultAppName);
    setAppDescriptionConfig(defaultAppDescription);
    setAppLogoConfig(defaultAppLogo || defaultLogo);
    setSceneImageConfig(defaultSceneImage || defaultLogo);
    setSceneImageOption(defaultSceneImage ? 'custom' : 'match');
  }, [open, defaultAppName, defaultAppDescription, defaultAppLogo, defaultSceneImage]);

  useEffect(() => {
    if (sceneImageOption === 'custom') {
      (!sceneImageConfig || sceneImageConfig === defaultLogo) && setSceneImageConfig('edu');
    }
  }, [sceneImageOption, appLogoConfig, sceneImageConfig]);

  // 预设场景图片
  const sceneImages: SceneImageType[] = [
    {
      id: 'edu',
      type: 'default',
      name: '校园',
    },
    {
      id: 'ent',
      type: 'enterprise',
      name: '企业',
    },
    {
      id: 'med',
      type: 'medical',
      name: '医疗',
    },
  ];

  const sceneImagesSpecial: SceneImageType[] = [
    {
      id: 'aiaa',
      type: 'AIAA',
      name: '招生助手',
    },
  ];

  const defaultSceneCustom = useMemo(() => {
    if (customSceneImages?.length > 0) {
      return customSceneImages?.[0];
    }
    if (defaultAppName && defaultAppName == '招生助手') {
      return 'aiaa';
    }
    return 'edu';
  }, [defaultAppName, customSceneImages]);

  const handleAppNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAppNameConfig(e.target.value);
  };
  const handleAppTagChange = (tag: string) => {
    setAppTag(tag);
  };

  const handleAppDescriptionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setAppDescriptionConfig(e.target.value);
  };

  const handleLogoSelect = (url: string) => {
    setAppLogoConfig(url);
  };

  const handleSceneImageOptionChange = (option: 'match' | 'custom') => {
    setSceneImageOption(option);
    if (option === 'custom') {
      setSceneImageConfig(defaultSceneCustom);
    } else {
      setSceneImageConfig('');
    }
  };

  const handleSceneImageSelect = (imageId: string) => {
    setSceneImageConfig(imageId);
  };

  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return false;
    }
    return true;
  };

  const logoBeforeUpload = (file: RcFile) => {
    if (!beforeUpload(file)) {
      return false;
    }
    if (customLogos.filter((logo) => !Object.keys(DEFAULT_IMAGES).includes(logo)).length >= 5) {
      message.warning('最多只能上传5张图片，请先删除已有图片。');
      return false;
    }
    return true;
  };

  const sceneImageBeforeUpload = (file: RcFile) => {
    if (!beforeUpload(file)) {
      return false;
    }
    if (customSceneImages.length >= 5) {
      message.warning('最多只能上传5张图片，请先删除已有图片。');
      return false;
    }
    return true;
  };
  const handleLogoUpload = async (file: File) => {
    setLogoLoading(true);
    try {
      const src = await compressImgFileAndUpload({
        type: MongoImageTypeEnum.appAvatar,
        file,
        maxW: 300,
        maxH: 300,
      });
      const url = new URL(src);
      const path = url.pathname.replace('//', '/');
      setCustomLogos((prev) => [path, ...prev]);
      setAppLogoConfig(path);
      message.success('Logo上传成功');
    } catch (error) {
      message.error('Logo上传失败');
    } finally {
      setLogoLoading(false);
    }
  };

  const handleLogoDelete = (logoUrl: string) => {
    setCustomLogos((prev) => prev.filter((url) => url !== logoUrl));
    if (appLogoConfig === logoUrl) {
      setAppLogoConfig(defaultLogo);
    }
  };

  const handleSceneImageUpload = async (file: File) => {
    setSceneImageLoading(true);
    try {
      const src = await compressImgFileAndUpload({
        type: MongoImageTypeEnum.appAvatar,
        file,
        maxW: 300,
        maxH: 300,
      });
      const url = new URL(src);
      const path = url.pathname.replace('//', '/');
      setCustomSceneImages((prev) => [path, ...prev]);
      setSceneImageConfig(path);
      message.success('场景图片上传成功');
    } catch (error) {
      message.error('场景图片上传失败');
    } finally {
      setSceneImageLoading(false);
    }
  };

  const handleSceneImageDelete = (imageUrl: string) => {
    setCustomSceneImages((prev) => prev.filter((url) => url !== imageUrl));
    if (sceneImageConfig === imageUrl) {
      setSceneImageConfig('edu');
    }
  };

  const logoUploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    beforeUpload: logoBeforeUpload,
    customRequest: ({ file }) => handleLogoUpload(file as File),
    disabled: false,
  };

  const sceneImageUploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    beforeUpload: sceneImageBeforeUpload,
    customRequest: ({ file }) => handleSceneImageUpload(file as File),
    disabled: false,
  };

  return (
    <Modals
      destroyOnHidden
      width={500}
      title={title}
      // title={<div className="text-center text-[19px] leading-[24px] text-[#000000]">
      //   {title}
      // </div>}
      open={isShow}
      onOk={async () => {
        if (!appNameConfig) {
          message.error('请输入应用名称');
          return;
        }
        if (sceneImageOption === 'custom') {
          if (!sceneImageConfig) {
            message.error('请上传场景图片');
          }
        }
        if (!isClick) return;

        if (onOk) {
          setIsClick(false);
          const resp = await onOk({
            appName: appNameConfig,
            tag: appTag,
            appDescription: appDescriptionConfig,
            appLogo: appLogoConfig,
            // sceneImage: sceneImageOption === 'match' ? appLogoConfig : sceneImageConfig,
            sceneImage: sceneImageOption === 'match' ? '' : sceneImageConfig,
            appLogoList: customLogos.filter(Boolean),
            sceneImageList: customSceneImages.filter(Boolean),
          });
          console.log(resp);
        }
      }}
      onCancel={() => {
        setIsShow(false);
        setAppTag(null);
        onCancel?.();
      }}
    >
      <Card className="card-module mb-4 overflow-hidden">
        <div className="mb-4 space-y-4">
          {/* 应用名称 */}
          <div>
            <CustomFormLabel
              className="mb-2"
              prefix
              required
              description="设置智能体应用的正式名称"
            >
              应用名称
            </CustomFormLabel>

            <div className="relative">
              <Input
                className="w-full focus:border-[#D9D9D9] focus:outline-none"
                value={appNameConfig}
                onChange={handleAppNameChange}
                placeholder="请输入内容"
                maxLength={20}
                disabled={false}
                style={{ paddingRight: '60px' }}
              />
              <div className="pointer-events-none absolute bottom-1 right-2 text-[14px] text-[#A5A9BB]">
                {appNameConfig.length || 0} / 20
              </div>
            </div>
          </div>

          {/* 应用描述（可选） */}
          <div>
            <CustomFormLabel
              className="mb-2"
              prefix
              description="在此填写关于该智能体应用功能的详细介绍和说明"
            >
              描述
            </CustomFormLabel>

            <div className="relative text-[14px] text-[#424242]">
              <Input.TextArea
                className="w-full resize-none rounded-lg border p-2 [-ms-overflow-style:none] [scrollbar-width:none] focus:border-[#D9D9D9] focus:outline-none"
                maxLength={200}
                placeholder="请输入内容"
                value={appDescriptionConfig}
                onChange={handleAppDescriptionChange}
                style={{ borderColor: '#D9D9D9', paddingBottom: '24px' }}
                autoSize={{ minRows: 4, maxRows: 6 }}
              />
              <div className="pointer-events-none absolute bottom-2 right-2 text-[14px] text-[#A5A9BB]">
                {appDescriptionConfig.length || 0} / 200
              </div>
            </div>
          </div>
          {/* 应用标签 */}
          <AppTagSelect className="w-full" value={appTag} needAdd tagChange={handleAppTagChange} />

          {/* 应用Logo */}
          <div className="flex">
            <PrefixStyleLabel className="mt-1" />
            <LogoSelector
              showTip
              appType={appType}
              uploadedLogoUrl={appLogoConfig}
              defaultAppName={defaultAppName}
              selectedLogoId={appLogoConfig}
              customLogos={customLogos}
              loading={logoLoading}
              onSelect={handleLogoSelect}
              onDelete={handleLogoDelete}
              uploadProps={logoUploadProps}
            />
          </div>

          {/* 场景图片 */}
          {/* <SceneImageSelector
            sceneImages={
              defaultAppName && defaultAppName == '招生助手'
                ? [...sceneImagesSpecial, ...sceneImages]
                : sceneImages
            }
            uploadedImageUrl={sceneImageConfig}
            selectedImage={sceneImageConfig}
            customSceneImages={customSceneImages}
            sceneImageOption={sceneImageOption}
            sceneImageLoading={sceneImageLoading}
            onOptionChange={handleSceneImageOptionChange}
            onImageSelect={handleSceneImageSelect}
            onImageDelete={handleSceneImageDelete}
            uploadProps={sceneImageUploadProps}
          /> */}
        </div>
      </Card>
    </Modals>
  );
};

export default AppInfoModal;
